package br.com.gerenteweb.daos;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.gerenteweb.loja.Loja;
import br.com.hibernate.util.HibernateUtil;

public class LojaDao implements Serializable {
	private Session sessao;
	private Transaction trans;
	private List<Loja> list;

	public void addLoja(Loja nLoja) {
		try {
			sessao = HibernateUtil.getSessionFactory().openSession();
			trans = sessao.beginTransaction();

			Loja loja = new Loja();

			loja.setRazaoSocial(nLoja.getRazaoSocial());
			loja.setFantasia(nLoja.getFantasia());
			loja.setCnpj(nLoja.getCnpj());
			loja.setEndereco(nLoja.getEndereco());
			loja.setContato(nLoja.getContato());

			sessao.save(loja);
			trans.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			sessao.close();
		}

	}

	public void removeLoja(Loja loja) {
		try {
			sessao = HibernateUtil.getSessionFactory().openSession();
			trans = sessao.beginTransaction();

			sessao.delete(loja);
			trans.commit();
		} catch (Exception e) {
			System.out.println("erro akii");
			e.printStackTrace();
			System.out.println("erro akii");
		} finally {
			sessao.close();
		}
	}

	public Loja getPorID(Long id) {
		Loja loja = null;
		try {
			sessao = HibernateUtil.getSessionFactory().openSession();
			trans = sessao.beginTransaction();
			loja = (Loja) sessao.get(Loja.class, id);
			trans.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			sessao.close();
		}
		return loja;
	}

	public List<Loja> getLojas() {
		sessao = HibernateUtil.getSessionFactory().openSession();
		trans = sessao.beginTransaction();

		Criteria cri = sessao.createCriteria(Loja.class);
		this.list = cri.list();
		sessao.flush();
		sessao.close();
		return list;
	}

	public Session getSessao() {
		return sessao;
	}

	public void setSessao(Session sessao) {
		this.sessao = sessao;
	}

	public Transaction getTrans() {
		return trans;
	}

	public void setTrans(Transaction trans) {
		this.trans = trans;
	}

	public List<Loja> getList() {
		return list;
	}

	public void setList(List<Loja> list) {
		this.list = list;
	}

	public void setLojas(List<Loja> lojas) {
		this.list = lojas;
	}

}
